package com.googlecode.cswish.struts.hibernate;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import javax.persistence.spi.PersistenceUnitInfo;

import org.hibernate.cfg.Configuration;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.ejb.HibernatePersistence;

//BAD design ! But I need the reference to Configuration & sessionFactory
public class HibernateJpaVendorAdapter extends
		org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter {
	
	// But the default spring provider doesn't keep the referece to Ejb3Configuration 
	// if there's not JNDI lsupport
	private static Map<String, Configuration> configurations = new HashMap<String, Configuration>();
	
	private final HibernatePersistence provider = new HibernatePersistence() {
		public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName,
				Map overridenProperties) {
			Ejb3Configuration cfg = new Ejb3Configuration();
			Ejb3Configuration configured = cfg.configure( persistenceUnitName, overridenProperties );
			Configuration configuration = configured.getHibernateConfiguration();
			configurations.put(persistenceUnitName, configuration);
			return configured != null ? configured.buildEntityManagerFactory() : null;
		}

		public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info,
				Map map) {
			Ejb3Configuration cfg = new Ejb3Configuration();
			Ejb3Configuration configured = cfg.configure( info, map ); 
			Configuration configuration = configured.getHibernateConfiguration();
			configurations.put(info.getPersistenceUnitName(), configuration);
			return configured != null ? configured.buildEntityManagerFactory() : null;
		}
	};
	
	public PersistenceProvider getPersistenceProvider() {
		return this.provider;
	}
	
	public static final Map<String, Configuration> getConfigurations() {
		return configurations;
	}
}